package reward

import (
	"math/rand"

	"gddgame.cc/galaxy/common/dsl/game"
	. "gddgame.cc/galaxy/common/dsl/game/item"
)

const providerName = "reward"

const RewardGiftLogicConfig = "RewardGiftLogic"

func init() {
	_ = game.RegisterGlobalModule(game.ModuleProvider{
		Name:    providerName,
		Depends: []string{"config", "item"},

		OnInit: func(env *game.Environment) error {
			if err := env.SetConfig(RewardGiftLogicConfig, [][]map[GiftType]int{}); err != nil {
				return err
			}
			return nil
		},
	})
}

func GenerateReward(env *game.Environment, logic *RewardLogic, reward *Reward, allItems map[int]*SettingItem) {
	// 随机生成
	// 金币获取
	if logic.GoldMax > 0 {
		reward.Gold += int(rand.Int31n(logic.GoldMax-logic.GoldMin+1) + logic.GoldMin)
	}
	// 道具获取
	if logic.ItemNumber > 0 {
		items := make(map[int]int)
		for i := int32(0); i < logic.ItemNumber; i++ {
			itemId := logic.GetItem()
			item := allItems[itemId]
			if _, ok := items[itemId]; !ok {
				items[itemId] = 0
			} else {
				i -= 1
				continue
			}
			// 道具数量获取
			number := 1
			if item.IsConsume {
				number += int(rand.Int31n(logic.ConsumeMax))
			}
			if item.Max > 0 && number > item.Max {
				number = item.Max
			}
			items[itemId] += number
		}
		reward.SetItems(items)
	}
	var RewardGiftLogic [][]map[GiftType]int
	if err := env.Config(RewardGiftLogicConfig, &RewardGiftLogic); err != nil {
		return
	}
	// 宝箱获取
	if logic.GiftStep > 0 {
		gifts := map[string]int{}
		g := RewardGiftLogic[logic.GiftStep][rand.Int31n(int32(len(RewardGiftLogic[logic.GiftStep])))]
		for key, value := range g {
			if value <= 0 {
				continue
			}
			gifts[string(key)] = int(value)
		}
		reward.SetGifts(gifts)
	}
}
